#encoding:utf-8
from flask import Flask, request, render_template, make_response, jsonify

import jwt
import pymysql
import hashlib
import datetime

app = Flask(__name__)
JWT_SALT = 'iv%x6xo7l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv='

from flask import Flask, request, render_template, make_response, jsonify, session
import pymysql
import hashlib

app = Flask(__name__)
app.secret_key = 'thisismy2021course'

def sql():
    # conn = pymysql.connect(host='localhost', user="root", passwd="f5a10ef2dd4f5e90", database="userLogin")
    conn = pymysql.connect(host='user-db', user="root", passwd="123456", database="userSys")
    cursor = conn.cursor()
    
    return conn, cursor

def md5(psd):
    m = hashlib.md5()
    m.update(psd.encode("utf8"))

    return m.hexdigest()

def create_token(payload):
    """
    :param payload:  例如：{'user_id':1,'username':'wupeiqi'}用户信息
    :return:
    """
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers)
    return result

    
@app.route("/", methods=['GET', 'POST'])
@app.route('/Page_Login_index.html', methods=['GET', 'POST'])
def hello():
    if request.method == "GET":
        return render_template("/Page_Login_index.html")
        
    if request.method == "POST":
        connect, cursor = sql()
        user = request.json
        username = user['username']
        password = user['password']

        sql_SelectName = "select uid, userPswd, is_del from users where userName Like \'%s\'" % username
        cursor.execute(sql_SelectName)
        try:
            userInfo = cursor.fetchone()
            userIs_del = userInfo[2]
            userPsd = userInfo[1]
            userId = userInfo[0]
            password_MD5 = str(md5(str(password)))
            
            if userIs_del == 1:
                cursor.close()
                connect.close()
                return make_response(jsonify({ 'msg': '', 'error': '该用户不存在！', 'userID': ''}), 200)
                
            else:
                
                if password_MD5 == userPsd:  # 如果登录成功
                    cursor.close()
                    connect.close()
                    jwtDecoderText = create_token({'userID': userId, 'userPsdMD5': password})
                    resp = make_response(jsonify({ 'msg': '{}'.format(jwtDecoderText) , 'error': '' , 'userID': userId}), 200)
                    return resp
                    
                else:
                    cursor.close()
                    connect.close()
                    return make_response(jsonify({ 'msg': '', 'error': '密码错误，登录失败！', 'userID': ''}), 200)
                    
        except:
            cursor.close()
            connect.close()
            return make_response(jsonify({ 'msg': '', 'error': '未查询到该用户，登录失败！', 'userID': ''}), 200)
            

app.run(host='0.0.0.0', port=3353)
